package com.weetop.akly.activity.mine;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.classic.adapter.BaseAdapterHelper;
import com.classic.adapter.CommonRecyclerAdapter;
import com.huawei.hms.hmsscankit.ScanUtil;
import com.huawei.hms.ml.scan.HmsScan;
import com.huawei.hms.ml.scan.HmsScanAnalyzerOptions;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.weetop.akly.R;
import com.weetop.akly.base.BaseActivity;
import com.weetop.akly.base.mvp.BaseModel;
import com.weetop.akly.bean.TrainItem;
import com.weetop.akly.presenter.TrainListPresent;
import com.weetop.akly.utils.BaseUtils;
import com.weetop.akly.view.TrainListView;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.yzq.zxinglibrary.common.Constant.DECODE;

public class TrainListActivity extends BaseActivity<TrainListPresent> implements TrainListView {

    private static final int CAMERA_REQ_CODE = 200;
    private static final int REQUEST_CODE_SCAN_ONE = 201;
    @BindView(R.id.tv_tl_title)
    TextView tvTlTitle;
    @BindView(R.id.tv_tl_right)
    TextView tvTlRight;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.rcy_record)
    RecyclerView rcyRecord;
    @BindView(R.id.srl_record)
    SmartRefreshLayout srlSpRecord;
    private ArrayList<TrainItem> data = new ArrayList<>();
    private boolean isRefresh, isLoadMore;
    private int page = 1;
    private String trainCode;
    private int REFRESH_DATA = 1200;

    @Override
    protected TrainListPresent createPresenter() {
        return new TrainListPresent(this, this);
    }

    private CommonRecyclerAdapter<TrainItem> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_trainlist);
        ButterKnife.bind(this);
        setToolBar("培训列表", "");
        intListView();
        mPresenter.getTrainList(page + "");
    }

    private void intListView() {
        rcyRecord.setItemAnimator(null);
        rcyRecord.setLayoutManager(new LinearLayoutManager(mActivity));
        srlSpRecord.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isLoadMore = true;
                page++;
                mPresenter.getTrainList(page + "");
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                isRefresh = true;
                page = 1;
                mPresenter.getTrainList(page + "");
            }
        });
    }

    @Override
    public void getTrainListSuccess(BaseModel<ArrayList<TrainItem>> o) {
        ArrayList<TrainItem> items = o.getData();
        showDataInList(items);
    }

    private void showDataInList(ArrayList<TrainItem> items) {
        if (adapter == null) {
            data.clear();
            data.addAll(items);
            adapter = new CommonRecyclerAdapter<TrainItem>(mActivity, R.layout.item_train, data) {
                @Override
                public void onUpdate(BaseAdapterHelper helper, TrainItem item, int position) {
                    helper.setText(R.id.tv_item_title, item.getTitle());

                    // 签到时间，0为未签到，进行扫码签到操作，不为0已签到，转判断exam_tim
                    helper.setVisible(R.id.tv_qiandao,View.GONE);
                    if ("0".equals(item.getSign_time())) {
                        helper.setText(R.id.tv_status, "未签到");
                        helper.setTextColor(R.id.tv_status, Color.parseColor("#787878"));
                        helper.setBackgroundRes(R.id.tv_status, R.drawable.bg_state_blacktag);
                        helper.setVisible(R.id.tv_qiandao,View.VISIBLE);
                        helper.setOnClickListener(R.id.tv_qiandao, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                requestPermission(CAMERA_REQ_CODE, DECODE);
                                trainCode = item.getCode();
                            }
                        });
                    } else if ("0".equals(item.getExam_time())) { // 考试时间，0为未考试，获取培训详情并考试，不为0为已考试，进入获取结果
                        helper.setText(R.id.tv_status, "未考试");
                        helper.setTextColor(R.id.tv_status, Color.parseColor("#787878"));
                        helper.setBackgroundRes(R.id.tv_status, R.drawable.bg_state_errortag);
                    } else {
                        helper.setText(R.id.tv_status, "已完成");
                        helper.setTextColor(R.id.tv_status, Color.parseColor("#4CCF72"));
                        helper.setBackgroundRes(R.id.tv_status, R.drawable.bg_state_oktag);
                    }
                    helper.setText(R.id.tv_one, "编号：" + item.getCode());
                    helper.setText(R.id.tv_two, "考核分值：" + item.getAll_score());
                    helper.setText(R.id.tv_three, "培训时间：" + item.getTrain_start_time() + "～" + item.getTrain_end_time());
                    helper.setText(R.id.tv_four, "考核时间：" + item.getExam_start_time() + "～" + item.getExam_end_time());
                }
            };
            rcyRecord.setAdapter(adapter);
            adapter.setOnItemClickListener((viewHolder, view, position) -> {
                TrainItem item = data.get(position);
                if (BaseUtils.fastClick()) {
                    if ("0".equals(item.getSign_time())) {//未签到，前往扫码签到
//                        requestPermission(CAMERA_REQ_CODE, DECODE);
//                        trainCode = item.getCode();
                    } else if ("0".equals(item.getExam_time())) {//未考试
                        Intent intent = new Intent(this, TrainDetailActivity.class);
                        intent.putExtra("train_code", data.get(position).getCode());
                        intent.putExtra("is_result", false);
                        startActivityForResult(intent, REFRESH_DATA);
                    } else {//已完成，前往考试结果
                        Intent intent = new Intent();
                        intent.putExtra("train_code", data.get(position).getCode());
                        intent.putExtra("is_result", true);
                        BaseUtils.toActivity(mActivity, TrainDetailActivity.class, intent);
                    }
                }
            });
        } else {
            if (isRefresh) {
                data.clear();
                data.addAll(items);
                srlSpRecord.finishRefresh(true);
                isRefresh = false;
                adapter.replaceAll(data);
            } else if (isLoadMore) {
                data.addAll(items);
                adapter.addAll(items);
                isLoadMore = false;
            }
        }
        if (items == null || items.size() < 10) {
            srlSpRecord.finishLoadMoreWithNoMoreData();
        } else {
            srlSpRecord.finishLoadMore(true);
        }
    }

    //动态申请权限
    private void requestPermission(int requestCode, int mode) {
        ActivityCompat.requestPermissions(
                this,
                new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE},
                requestCode);
    }

    //在权限申请回调中启动扫码界面
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (permissions == null || grantResults == null) {
            return;
        }
        if (grantResults.length < 2 || grantResults[0] != PackageManager.PERMISSION_GRANTED || grantResults[1] != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        if (requestCode == CAMERA_REQ_CODE) {
            ScanUtil.startScan(this, REQUEST_CODE_SCAN_ONE, new HmsScanAnalyzerOptions.Creator().setPhotoMode(true).setHmsScanTypes(HmsScan.QRCODE_SCAN_TYPE).create());
        }
    }

    //在activity回调里面获取码结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK || data == null) {
            return;
        }
        if (requestCode == REQUEST_CODE_SCAN_ONE) {
            HmsScan obj = data.getParcelableExtra(ScanUtil.RESULT);
            if (obj != null) {
                mPresenter.doTrainSign(obj.originalValue, trainCode);
            }
        } else if (requestCode == REFRESH_DATA) {
            srlSpRecord.autoRefresh();
        }
    }

    @Override
    public void doTrainSignSuccess(BaseModel<Boolean> o) {
        if (o.getData()) {
            ToastUtils.showShort("签到成功");
            srlSpRecord.autoRefresh();
        } else {
            ToastUtils.showShort(o.getMsg());
        }
    }
}